const axios = require('axios');

const NAS_URL = 'http://192.168.0.177:5000'; // 你的群晖地址

function encodePathParam(path) {
  return path;
}

// 登录，获取 sid
async function login(account, passwd) {
  const params = {
    api: 'SYNO.API.Auth',
    version: 3,
    method: 'login',
    account,
    passwd,
    session: 'FileStation',
    format: 'sid'
  };
  const url = `${NAS_URL}/webapi/auth.cgi`;
  console.log('最终请求URL:', url + '?' + new URLSearchParams(params).toString());
  const res = await axios.get(url, { params });
  if (res.data && res.data.data && res.data.data.sid) {
    return res.data.data.sid;
  } else {
    throw new Error('登录失败: ' + JSON.stringify(res.data));
  }
}

// 用 sid 查询文件夹下的文件列表
async function listFiles(sid, folder_path) {
  const params = {
    api: 'SYNO.FileStation.List',
    version: 2,
    method: 'list',
    folder_path: encodePathParam(folder_path),
    _sid: sid
  };
  console.log('群晖listFiles params:', params);
  const url = `${NAS_URL}/webapi/entry.cgi`;
  console.log('最终请求URL:', url + '?' + new URLSearchParams(params).toString());
  const res = await axios.get(url, { params });
  return res.data;
}

// 查询共享文件夹列表
async function listShare(sid) {
  const params = {
    api: 'SYNO.FileStation.List',
    version: 2,
    method: 'list_share',
    _sid: sid
  };
  console.log('群晖listShare params:', params);
  const url = `${NAS_URL}/webapi/entry.cgi`;
  console.log('最终请求URL:', url + '?' + new URLSearchParams(params).toString());
  const res = await axios.get(url, { params });
  return res.data;
}

// 上传文件
async function uploadFile(sid, folder_path, file) {
  const FormData = require('form-data');
  const fs = require('fs');
  const form = new FormData();
  form.append('api', 'SYNO.FileStation.Upload');
  form.append('version', 2);
  form.append('method', 'upload');
  form.append('path', encodePathParam(folder_path));
  form.append('_sid', sid);
  form.append('overwrite', 'true');
  form.append('create_parents', 'true');
  form.append('file', fs.createReadStream(file.path), file.originalname);
  console.log('群晖uploadFile params:', {
    api: 'SYNO.FileStation.Upload',
    version: 2,
    method: 'upload',
    path: encodePathParam(folder_path),
    _sid: sid,
    overwrite: 'true',
    create_parents: 'true',
    file: file.originalname
  });
  const url = `${NAS_URL}/webapi/entry.cgi`;
  const headers = form.getHeaders();
  // 打印最终请求URL和表单参数
  console.log('最终请求URL:', url + '?' + new URLSearchParams({
    api: 'SYNO.FileStation.Upload',
    version: 2,
    method: 'upload',
    path: encodePathParam(folder_path),
    _sid: sid,
    overwrite: 'true',
    create_parents: 'true'
  }).toString());
  console.log('最终表单参数:', {
    api: 'SYNO.FileStation.Upload',
    version: 2,
    method: 'upload',
    path: encodePathParam(folder_path),
    _sid: sid,
    overwrite: 'true',
    create_parents: 'true',
    file: file.originalname
  });
  try {
    const res = await axios.post(url, form, { headers });
    return res.data;
  } catch (e) {
    console.error('上传失败:', e.response?.data || e.message);
    throw e;
  }
}

// 复制文件或文件夹
async function copyFile(sid, src, dest_folder_path) {
  const params = {
    api: 'SYNO.FileStation.CopyMove',
    version: 2,
    method: 'copy',
    path: encodePathParam(src),
    dest_folder_path: encodePathParam(dest_folder_path),
    _sid: sid
  };
  console.log('群晖copyFile params:', params);
  const url = `${NAS_URL}/webapi/entry.cgi`;
  console.log('最终请求URL:', url + '?' + new URLSearchParams(params).toString());
  const res = await axios.get(url, { params });
  return res.data;
}

// 非阻塞删除
async function deleteFile(sid, path) {
  const params = {
    api: 'SYNO.FileStation.Delete',
    version: 2,
    method: 'start',
    path: encodePathParam(path),
    _sid: sid
  };
  console.log('群晖deleteFile params:', params);
  const url = `${NAS_URL}/webapi/entry.cgi`;
  console.log('最终请求URL:', url + '?' + new URLSearchParams(params).toString());
  const res = await axios.get(url, { params });
  return res.data;
}
// 查询删除进度
async function deleteStatus(sid, taskid) {
  const params = {
    api: 'SYNO.FileStation.Delete',
    version: 2,
    method: 'status',
    taskid,
    _sid: sid
  };
  console.log('群晖deleteStatus params:', params);
  const url = `${NAS_URL}/webapi/entry.cgi`;
  console.log('最终请求URL:', url + '?' + new URLSearchParams(params).toString());
  const res = await axios.get(url, { params });
  return res.data;
}

// 非阻塞移动文件或文件夹
async function moveFile(sid, src, dest_folder_path) {
  let pathParam;
  if (Array.isArray(src)) {
    pathParam = src.length === 1 ? src[0] : src;
  } else {
    pathParam = src;
  }
  const params = {
    api: 'SYNO.FileStation.CopyMove',
    version: 3,
    method: 'start',
    path: pathParam,
    dest_folder_path: dest_folder_path,
    remove_src: 'true',
    _sid: sid
  };
  console.log('群晖move params:', params);
  const url = `${NAS_URL}/webapi/entry.cgi`;
  console.log('最终请求URL:', url + '?' + new URLSearchParams(params).toString());
  const res = await axios.get(url, { params });
  return res.data;
}

// 下载文件（返回文件流）
async function downloadFile(sid, file_path, res) {
  const params = {
    api: 'SYNO.FileStation.Download',
    version: 2,
    method: 'download',
    path: encodePathParam(file_path),
    _sid: sid
  };
  console.log('群晖downloadFile params:', params);
  const url = `${NAS_URL}/webapi/entry.cgi`;
  console.log('最终请求URL:', url + '?' + new URLSearchParams(params).toString());
  const response = await axios.get(url, { params, responseType: 'stream' });
  res.setHeader('Content-Disposition', response.headers['content-disposition'] || `attachment; filename="${encodeURIComponent(file_path.split('/').pop())}"`);
  res.setHeader('Content-Type', response.headers['content-type'] || 'application/octet-stream');
  response.data.pipe(res);
}

// 新建文件夹
async function createFolder(sid, parent_path, name) {
  const params = {
    api: 'SYNO.FileStation.CreateFolder',
    version: 2,
    method: 'create',
    folder_path: parent_path, // 不做编码
    name,
    _sid: sid
  };
  console.log('群晖createFolder params:', params);
  const url = `${NAS_URL}/webapi/entry.cgi`;
  console.log('最终请求URL:', url + '?' + new URLSearchParams(params).toString());
  const res = await axios.get(url, { params });
  return res.data;
}

// 创建分享链接
async function createSharing(sid, path) {
  const params = {
    api: 'SYNO.FileStation.Sharing',
    version: 3,
    method: 'create',
    path,
    _sid: sid
  };
  const url = `${NAS_URL}/webapi/entry.cgi`;
  const res = await axios.get(url, { params });
  return res.data;
}

module.exports = {
  login,
  listFiles,
  listShare,
  uploadFile,
  copyFile,
  deleteFile,
  moveFile,
  downloadFile,
  createFolder,
  deleteStatus, // 新增导出
  createSharing // 新增导出
}; 